package puzzle.platformer.game;

import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.View.OnTouchListener;
 
public class puzzleActivity extends Activity{
	private Panel panel;
	public GameThread _thread;
	private LevelFileReader _reader;
	
	@Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        panel = new Panel(this);
        _reader = new LevelFileReader(this,panel);
        setContentView(panel);
        try{
			_reader.readFileLevel("level_1");
		} 
        catch (IOException e1){
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
        panel.setOnTouchListener(new OnTouchListener(){  
            public boolean onTouch(View v,MotionEvent e){ 
            	int x = (int) e.getX();
            	int y = (int) e.getY();
               panel.handleInput(e,x,y);
               return false;
            }  
        }); 
    }
 
    class Panel extends SurfaceView implements SurfaceHolder.Callback{
        private Player player;
        private Grid grid;
        private Paint paint;//voor als je text wil drawen
        private String temp = "";
        private int moveamount = 0;
        private int jumpamount = 0;
    	
        public Panel(Context context){
            super(context);
            getHolder().addCallback(this);
            _thread = new GameThread(getHolder(), this); 
            player = new Player();
            grid = new Grid();
            paint = new Paint();
            paint.setColor(Color.BLACK);
        	paint.setStyle(Paint.Style.FILL);
            paint.setAntiAlias(true);
            paint.setTextSize(20);
        }
       
        public void handleInput(MotionEvent e, int x, int y){
        	temp = x + " " + y;
        	if(e.getAction() == MotionEvent.ACTION_DOWN){
        		if(x >= 10 && x <= 60){
        			if(y >= this.getHeight()-50 && y <= this.getHeight())
        				moveamount = -5;
        		}
        		else if(x >= 110 && x <= 160){
        			if(y >= this.getHeight()-50 && y <= this.getHeight())
        				moveamount = 5;
        		}
        		else if(x >= this.getWidth()-60 && x <= this.getWidth()-10){
        			if(y >= this.getHeight()-50 && y < this.getHeight())
        				jumpamount = 10;
        		}
        	}
        	temp = x + " " + y;
        }
        
        public void movePlayer(){
        	if(checkCollisionX() == false && checkCollisionY() == false){
        		player.moveX(moveamount);
        	}
        	if(checkCollisionY() == false){
        		player.moveY(jumpamount);
        		jumpamount -= 1;
        	}
        	else{
        		jumpamount = 0;
        	}
        }
        
        public void clearLevel(){
        	grid.clearCells();
        }
        
        public void addBlock(int x, int y, int imageid, int width){
        	grid.addCell(x, y, imageid, width);
        }
        
        public void setPlayer(int x, int y, int imageid, int width, int height){
        	player.setValues(x, y, imageid, width, height);
        }
        
        public boolean checkCollisionX(){
        	boolean collision = false;
        	for(int i = 0; i < grid.getCellAmount(); i++){
        		if(moveamount > 0){  //if player moves right      	
        			if(grid.getCellX(i) > player.getX()){
        				if(grid.getCellLeftX(i) == player.getRightX() || (grid.getCellLeftX(i) - player.getRightX()) < 5)
        					collision = true;
        			}
        		}
        		else if(moveamount < 0){  //if player moves right      	
        			if(grid.getCellX(i) < player.getX()){
        				if(grid.getCellRightX(i) == player.getLeftX() || (player.getLeftX() - grid.getCellRightX(i)) < 5)
        					collision = true;
        			}
        		}
        	}
        	return collision;
        }
        
        public boolean checkCollisionY(){
        	boolean collision = false;
        	for(int i = 0; i < grid.getCellAmount(); i++){
        		if(jumpamount < 0){  //if player moves down    	
        			if(grid.getCellY(i) > player.getY()){
        				if(grid.getCellTopY(i) == player.getBottomY() || (player.getBottomY() - grid.getCellTopY(i)) > (jumpamount-1)){
        					if(player.getLeftX() > grid.getCellLeftX(i) && player.getLeftX() < grid.getCellRightX(i)){
        						collision = true;
        					}
        					else if(player.getRightX() < grid.getCellRightX(i) && player.getRightX() > grid.getCellLeftX(i)){
        						collision = true;
        					}
        				}
        					
        			}
        		}
        	}
        	return collision;
        }
       
        @Override
        public void onDraw(Canvas canvas){
        	//witte achtergrond kleur
        	canvas.drawColor(Color.WHITE);
        	//schermbreedte en hoogte
            int screenwidth = this.getWidth();
            int screenheight = this.getHeight();
            //drawen blocks
        	for(int i = 0; i < grid.getCellAmount(); i ++){
        		if(grid.getCellX(i) > player.getX()-screenwidth/2 || grid.getCellX(i) < player.getX()+screenwidth/2){
        			Bitmap block = BitmapFactory.decodeResource(getResources(),grid.getCellImageId(i)); 
        			canvas.drawBitmap(block, screenwidth/2+(grid.getCellX(i)-player.getX()), screenheight-grid.getCellY(i)-100, null);
        		}
        	}
        	//draw player
        	Bitmap player_img = BitmapFactory.decodeResource(getResources(),R.drawable.player); 
    		canvas.drawBitmap(player_img, screenwidth/2, screenheight-player.getY()-100, null);
    		//draw buttons
    		Bitmap button_left = BitmapFactory.decodeResource(getResources(),R.drawable.button_right); 
    		canvas.drawBitmap(button_left, 10, screenheight-50, null);
    		Bitmap button_right = BitmapFactory.decodeResource(getResources(),R.drawable.button_left); 
    		canvas.drawBitmap(button_right, 110, screenheight-50, null);
    		Bitmap button_jump = BitmapFactory.decodeResource(getResources(), R.drawable.button_jump);
    		canvas.drawBitmap(button_jump, screenwidth-60, screenheight-50, null);
    		
    		canvas.drawText(temp, 300, 300,paint);
        }
 
        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height){
            // TODO Auto-generated method stub
        }
 
        @Override
        public void surfaceCreated(SurfaceHolder holder){
            _thread.setRunning(true);
            _thread.start();
        }
 
        @Override
        public void surfaceDestroyed(SurfaceHolder holder){
            // simply copied from sample application LunarLander:
            // we have to tell thread to shut down & wait for it to finish, or else
            // it might touch the Surface after we return and explode
            boolean retry = true;
            _thread.setRunning(false);
            while (retry){
                try{
                    _thread.join();
                    retry = false;
                } 
                catch (InterruptedException e){
                    // we will try it again and again...
                }
            }
        }
    }
 
    class GameThread extends Thread{
        private SurfaceHolder _surfaceHolder;
        private Panel _panel;
        private boolean _run = false;
 
        public GameThread(SurfaceHolder surfaceHolder, Panel panel){
            _surfaceHolder = surfaceHolder;
            _panel = panel;
        }
 
        public void setRunning(boolean run){
            _run = run;
        }
 
        @Override
        public void run(){
            Canvas c;
            while (_run){
                c = null;
                try{
                    c = _surfaceHolder.lockCanvas(null);
                    synchronized (_surfaceHolder){
                    	_panel.movePlayer();
                        _panel.onDraw(c);
                    }
                } 
                finally{
                    // do this in a finally so that if an exception is thrown
                    // during the above, we don't leave the Surface in an
                    // inconsistent state
                    if (c != null)
                        _surfaceHolder.unlockCanvasAndPost(c);
                }
            }
        }
    }
}